import { NextResponse } from 'next/server';
import { PrismaClient } from '@prisma/client';
import * as crypto from 'crypto';

const prisma = new PrismaClient();

// 创建密码哈希
function createPasswordHash(password: string): { hash: string, salt: string } {
  const salt = crypto.randomBytes(16).toString('hex');
  const hash = crypto.pbkdf2Sync(
    password,
    salt,
    10000, // 迭代次数
    64,    // 密钥长度
    'sha512'
  ).toString('hex');
  
  return { hash, salt };
}

export async function POST(request: Request) {
  try {
    // 检查是否设置了安全密钥
    const setupKey = process.env.ADMIN_SETUP_KEY;
    if (!setupKey) {
      return NextResponse.json(
        { message: '未配置安全密钥，不允许设置管理员' },
        { status: 403 }
      );
    }

    const body = await request.json();
    const { username, password, key } = body;
    
    // 验证安全密钥
    if (key !== setupKey) {
      return NextResponse.json(
        { message: '无效的安全密钥' },
        { status: 403 }
      );
    }
    
    // 验证必要参数
    if (!username || !password) {
      return NextResponse.json(
        { message: '用户名和密码不能为空' },
        { status: 400 }
      );
    }
    
    // 检查是否已经存在管理员账户
    const adminCount = await prisma.player.count({
      where: { isAdmin: true }
    });
    
    if (adminCount > 0) {
      return NextResponse.json(
        { message: '已存在管理员账户，无法再次设置初始账户' },
        { status: 400 }
      );
    }
    
    // 创建密码哈希
    const { hash, salt } = createPasswordHash(password);
    
    // 创建管理员用户
    const admin = await prisma.player.create({
      data: {
        name: username,
        avatar: "/default-admin.jpg",
        region: "管理团队",
        isAdmin: true
      }
    });
    
    // 更新用户密码
    await prisma.$executeRaw`
      UPDATE Player 
      SET passwordHash = ${hash}, passwordSalt = ${salt}
      WHERE id = ${admin.id}
    `;
    
    // 创建权限
    const permissionTypes = [
      "USER_MANAGE", "SETTINGS_MANAGE", 
      "SWORD_MODIFY", "CRYSTAL_MODIFY", "BUHC_MODIFY",
      "POTION_MODIFY", "NPOT_MODIFY", "SMP_MODIFY"
    ];
    
    // 使用原始SQL创建权限
    for (const permType of permissionTypes) {
      await prisma.$executeRaw`
        INSERT INTO Permission (playerId, permissionType)
        VALUES (${admin.id}, ${permType})
      `;
    }
    
    return NextResponse.json({
      message: '管理员账户创建成功',
      admin: {
        id: admin.id,
        name: admin.name,
        avatar: admin.avatar,
        isAdmin: admin.isAdmin
      }
    });
    
  } catch (error) {
    console.error('设置管理员错误:', error);
    
    // 检查是否是唯一性约束错误
    const errorMessage = String(error);
    if (errorMessage.includes('Unique constraint')) {
      return NextResponse.json(
        { message: '用户名已存在' },
        { status: 400 }
      );
    }
    
    return NextResponse.json(
      { message: '创建管理员账户过程中发生错误' },
      { status: 500 }
    );
  }
} 